import React, {
    Component
} from 'react';
import ReactDOM from 'react-dom';
import {
    observable,
    action,
    computed,
    toJS,
} from 'mobx';
import {
    ListAdvanced,
    SearchAdvanced,
    RouteLayout,
    Form,
    BrowserHrm,
    ListViewPage,
    SelectLinkage,
} from 'weaver-mobile-page';
import {
    Tools,
    Bubble
} from 'weaver-mobile';
import DeleteConfirm from "../../util/DELUtil.js";
import { configNavigation } from "../../util/public-func";
import * as api from '../../apis/group.js';
const getLabel = Tools.getLabel;

export class GroupStore {
    history = null;
    isEdit = false;
    @observable source = "main";
    @observable showCheck = false; //ListAdvanced组件属性，控制check框是否显示
    @observable popoverVisible = false;
    @observable tabKey = "1"; //新建常用组页面当前所在的页签
    @observable suggestTabKey = "0";
    @observable browserHrmValue = []; //多人力浏览按钮返回的数据
    @observable groupType = "0"; //常用组类型
    @observable isHas = false; //是否有公共组调整建议
    @observable isHasNew = false; //是否有调整建议
    @observable suggestDetail = {};

    @computed get baseRoute() {
        return (this.source === "main") ? "/group/operate" : "/groupOp";
    }


    @observable groupListAd = new ListAdvanced.Store({
        route: '/group',
    });

    @observable operateGrouplayout = new RouteLayout.Store({
        route: '/group',
        id: "operate"
    });

    @observable basicForm = new Form.Store({
        route: '/group/operate',
    });

    @observable memberListAd = new ListViewPage.Store({
        route: '/group/operate',
    });

    @observable browserHrmStore = new BrowserHrm.Store({
        route: '/group/operate',
        id: 'mulHrm'
    });

    @observable shareListStore = new ListViewPage.Store({
        route: '/group/operate',
    });

    @observable shareScopeAddlayout = new RouteLayout.Store({
        route: '/group/operate',
        id: "addShare"
    });

    @observable shareForm = new Form.Store({
        route: '/group/operate/addShare',
    });

    @observable suggestlayout = new RouteLayout.Store({
        route: '/group',
        id: "suggest"
    });

    @observable suggestListStore = new ListViewPage.Store({
        route: '/group/suggest',
    });

    @observable suggestSearchStore = new SearchAdvanced.Store({
        route: '/group/suggest',
        id: "search"
    });

    @observable suggestDetaillayout = new RouteLayout.Store({
        route: '/group/suggest',
        id: "detail"
    });

    //新建常用组页签
    @computed get tabs() {
        const {
            type
        } = this.basicForm.formParams;

        const __type = type || this.groupType;

        const tabs = [{
            key: "1",
            title: getLabel(505832, '基本信息')
        }, {
            key: "2",
            title: getLabel(431, '成员')
        }];

        if (__type == '1') {
            tabs.push({
                key: "3",
                title: getLabel(82752, '共享范围')
            });
        }

        return tabs
    }

    @computed get suggestDetailBtns() {
        const { suggesttype, namespan, contentspan } = this.suggestDetail;
        if (!suggesttype) return
        const datas = [{
            key: 'markAs',
            text: getLabel('518814', '标记为已处理'),
            onClick: () => this.markAsRead(this.suggestDetail, true)

        }];

        if (suggesttype === "1") {
            datas.push({
                key: "add",
                text: getLabel('518813', '确认添加'),
                onClick: () =>{
                	const div = document.createElement("div");
        			document.body.appendChild(div);
					
					ReactDOM.render(<DeleteConfirm 
						msg={ getLabel(520367,'确定将 {params1} 加入组“{params2}”吗？').replace("{params1}",contentspan).replace("{params2}", namespan)  }
						handleOk={() => this.confirmAdd(this.suggestDetail,true)}
					/>, div)
                },
                type: 'primary',
            })
        } else {
            datas.push({
                key: "del",
                text: getLabel('518815', '确认删除'),
                onClick: () =>{
                	const div = document.createElement("div");
        			document.body.appendChild(div);

        			ReactDOM.render(<DeleteConfirm 
						msg={ getLabel(520368, "确定将 {params1} 从组“{params2}”中删除吗？").replace("{params1}",contentspan).replace("{params2}", namespan) }
						handleOk={() => this.confirmDel(this.suggestDetail, true)}
					/>, div)
                },
                type: 'primary',
            })
        }

        return datas;
    }

    initSuggest = () => {
        this.suggestTabKey = "0";
        this.getSuggestSearchCondition();
        this.getSuggestList();
    }

    @action getSuggestSearchCondition = () => {
        const suggestSearchStore = this.suggestSearchStore;
        suggestSearchStore.responseKey = "condition";
        suggestSearchStore.getData({
            url: "/api/hrm/group/getSearchCondition?cmd=suggest",
        });
    }

    @action getSuggestList = (datas = {}) => {
        const params = {
            cmd: "suggest",
            status: this.suggestTabKey,
            ...this.suggestSearchStore.form.formParams,
            ...datas
        };
        this.suggestListStore.clearData();
        api.getSearchResult(params).then(res => {
            const { sessionkey, datas } = res;
            if (sessionkey) {
                this.suggestListStore.getData({
                    dataKey: sessionkey
                });
            }
            if (datas && datas[0]) {
                this.suggestDetail = datas[0];
            }
        })
    }

    @action getGroupList = () => {
        const { listViewStore } = this.groupListAd;
        listViewStore.clearData();
        listViewStore.selectedRowKeys = [];
        this.groupListAd.getData({
            url: '/api/hrm/group/getSearchResult',
            method: 'POST',
            params: {
                cmd: "base",
                ...this.getQueryParams()
            }
        });
    }

    @action getGroupSearchCondition = () => {
        const searchAdvancedStore = this.groupListAd.searchAdvancedStore;
        searchAdvancedStore.responseKey = "condition";
        searchAdvancedStore.getData({
            url: "/api/hrm/group/getSearchCondition?cmd=base",
            method: 'GET',
        });
    }

    @action handlePopoverSelect = (opt) => {
        switch (opt.key) {
            case "1":
                document.title = getLabel(386496, "新建常用组");
                this.isEdit = false;
                this.groupid = "";
                this.setTabKey("1");
                //打开新建常用组layout
                this.history && this.history.push(this.operateGrouplayout.path);
                break;
            case "2":
                this.showCheck = true;
                break;
            case "3":
                this.history && this.history.push(this.suggestlayout.path);
                break;
        }
        //隐藏Popover
        this.handleVisibleChange(false);
    }

    //获取表单信息:基本信息、添加共享
    @action getForm = (datas) => {
        const params = {
            cmd: "base",
        };
        if ((params.cmd === "base") && this.groupid) {
            Object.assign(params, {
                groupid: this.groupid
            });
        };
        Object.assign(params, datas);

        api.getHrmGroupForm(params).then((res) => {
            const { condition } = res;
            const cmd = params.cmd;

            const route = `${ (cmd === "base") ? this.baseRoute : `${ this.baseRoute }/addShare` }`;
            const name = (cmd === "base") ? "basicForm" : "shareForm";

            this[name] = new Form.Store({
                route
            });

            if (condition) {
                if (cmd === "share") {
                    //调换数据的顺序
                    const alllevel = condition[0].items.pop();
                    condition[0].items.splice(-1, 0, alllevel);
                    //设置安全级别默认值
                    condition.map(c => c.items.map(item => {
                        const key = item.domkey[0];
                        if (key === "seclevel") {
                            item.startValue = "0";
                            item.endValue = "100";
                        }
                    }));
                }

                this[name].initForm(condition, route);
                if (this.source === "op" && this.groupType =="1") {
                    this.basicForm.updateField("type", this.groupType)
                }
            }

        })
    }

    @action getAdviceInfo = () => {
        return new Promise((resolve, reject) => {
            const params = {
                cmd: "isHasSuggest",
            }
            api.getSearchResult(params).then(datas => {
                const { status, isHas, isHasNew } = datas;

                if (status == 1) {
                    this.isHas = (isHas === 1);
                    this.isHasNew = (isHasNew === 1);
                    resolve();
                } else {
                    Bubble.warning(datas.message);
                    reject();
                }
            })
        })
    }

    //切换页签
    @action setTabKey = (key) => {
        const handleTabClick = () => {
            this.tabKey = key;

            if (key === "1") {
                this.getForm();
            }
        }

        //从基本信息页签切换到其他页签时，需要保存表单来获取群组的id
        if (this.tabKey === "1" && key !== "1") {
            //这里保存成功后，不需要弹出提示信息
            this.saveBasicInfo(false, handleTabClick);
        } else {
            handleTabClick()
        }

    }

    //value: 选中人员id的集合
    //选中人员后，保存人员信息并刷新成员列表
    @action setBrowserHrmValue = (value) => {
        const params = {
            cmd: "member",
            groupid: this.groupid,
            members: value
        };
        //第二个参数为保存成功后的回调
        this.save(params, () => {
            this.getMemberList()
        });

    }

    //保存基本信息
    saveBasicInfo = (showMsg = true, callback) => {
        //提示信息居中，放弃调用组件的doValidate方法
        // const result = this.basicForm.doValidate();
        const { name } = this.basicForm.formParams;
        if (name) {
            const params = {
                cmd: "base",
                ...this.basicForm.formParams
            };
            if (this.groupid) {
                Object.assign(params, {
                    groupid: this.groupid
                });
            }

            if (this.source == "op") {
                if (!callback) {
                    callback = () =>{
                        
                    }
                }
            }
            this.save(params, callback, showMsg);
        }else{
            if (this.tabKey == "1") {
                Bubble.warning(getLabel('521503','名称未填写'));
            }else{
                //这边不是真正的保存成功，只是一个提示
                Bubble.success(getLabel(83551, '保存成功！'));
            }
        }
    }   
    
    doValidate = () => {
        const { sharetype,rsid,sbid,did ,rid,jobtitle,customid,seclevel,seclevelto,jobtitlelevel,jobtitlesubcompany,jobtitledepartment} = this.shareForm.formParams;
        
        if (
            (sharetype == "1" && !rsid) ||
            (sharetype == "2" && !sbid) ||
            (sharetype == "3" && !did) ||
            (sharetype == "4" && !rid) ||
            (sharetype == "7" && !jobtitle) ||
            (sharetype == "8" && !customid)
        ) {
            Bubble.warning(getLabel('521504','对象未填写'));
            return false;
        }

        if (["2","3","4","8","5"].includes(sharetype)) {
             //不操作安全级别， 从this.shareForm.formParams中获取不到安全级别
           const arr = this.shareForm.formData.seclevel__seclevelto;
            
            const a = seclevel || arr[0],
            b = seclevelto || arr[1];

            if(!a || !b){
                 Bubble.warning(getLabel('521505','安全级别未填写'));
                 return false;
            }
        }

        if (sharetype == "7") {
            if (jobtitlelevel == "1" && !jobtitledepartment) {
                Bubble.warning(getLabel('521506','指定部门未填写'));
                 return false;
            }
            if (jobtitlelevel == "2" && !jobtitlesubcompany) {
                Bubble.warning(getLabel('521507','指定分部未填写'));
                 return false;
            }
        }

        return true;
    }

    //保存共享范围
    saveShareScope = () => {
        const pass = this.doValidate();
        if (pass) {
            const params = {
                cmd: "share",
                groupid: this.groupid,
                ...this.shareForm.formParams
            };

            if (params.seclevel) {
                params.seclevelTo = params.seclevelto;
            } else {
                //不操作安全级别， 从this.shareForm.formParams中获取不到安全级别
                const [seclevel, seclevelTo] = this.shareForm.formData.seclevel__seclevelto;

                Object.assign(params, {
                    seclevel,
                    seclevelTo,
                });
            }

            this.save(params, () => {
                configNavigation(getLabel(518812, "编辑常用组"));
                this.history && this.history.go(-1);
                this.getShareList();
            });
        }
    }

    //params:保存接口所需的参数
    //callback：保存成功后执行的回调函数
    //showMsg：是否显示保存成功的提示信息，默认显示
    save = (params, callback, showMsg = true) => {
        api.save(params).then(datas => {
            const {
                message,
                groupid,
                status
            } = datas;

            if (status === "1") {
                showMsg && Bubble.success(message || getLabel(22619, "保存成功"));
                if (groupid) {
                    this.groupid = groupid;
                }
                callback && callback();
            } else {
                Bubble.warning(message || getLabel(84544,"保存失败！"));
            }
        })
    }

    //获取共享范围列表信息
    @action getShareList = () => {
        const params = {
            cmd: "share",
            groupid: this.groupid
        }
        this.shareListStore.clearData();
        api.getSearchResult(params).then(datas => {
            if (datas.sessionkey) {
                this.shareListStore.getData({
                    dataKey: datas.sessionkey
                });
            }
        })

    }

    @action del = (params) => {
        return new Promise((resolve, reject) => {
            api.del(params).then(datas => {
                const {
                    status
                } = datas;

                if (status === "1") {
                    resolve();
                } else {
                    Bubble.warning(datas.message || getLabel(20462, "删除失败"));
                    reject();
                }
            })
        })
    }

    //获取成员列表信息
    @action getMemberList = () => {
        const params = {
            cmd: "member",
            groupid: this.groupid
        }
        this.memberListAd.clearData();
        api.getSearchResult(params).then(datas => {
            if (datas.sessionkey) {
                this.memberListAd.getData({ dataKey: datas.sessionkey });
            }
        })
    }

    @action handleVisibleChange = (bool) => {
        this.popoverVisible = bool;
    }

    @action changeSuggestTabKey = (key) => {
        this.suggestTabKey = key;
        this.getSuggestList();
    }

    @action setSource = (source) => {
        this.source = source;
    }

    confirmAdd = (data, isBack) => {
        const params = {
            cmd: "doAdd",
            id: data.randomFieldId || data.id
        };
        api.save(params).then(datas => {
            const { message, status } = datas;

            if (status == 1) {
                Bubble.success(message);
                this.getSuggestList();
                //单页保存后，调用closeWindow关闭当前页面
                if (this.source === "suggest") {
                    if (window.em && window.em.checkJsApi('closeWindow')) {
                        window.em.closeWindow({
                            fail: (msg) => {
                                Bubble.error(JSON.stringify(msg))
                            }
                        });
                    }
                    return;
                }
                if (isBack) {
                    this.history && this.history.go(-1)
                }


            } else {
                Bubble.warning(message);
            }
        })
    }

    confirmDel = (data, isBack) => {
        const params = {
            cmd: "doDel",
            id: data.randomFieldId || data.id
        };
        api.del(params).then(datas => {
            const { message, status } = datas;

            if (status == 1) {
                Bubble.success(message);
                this.getSuggestList();
                if (this.source === "suggest") {
                    if (window.em && window.em.checkJsApi('closeWindow')) {
                        window.em.closeWindow({
                            fail: (msg) => {
                                Bubble.error(JSON.stringify(msg))
                            }
                        });
                    }
                    return;
                }
                if (isBack) {
                    this.history && this.history.go(-1)
                }
            } else {
                Bubble.warning(message);
            }
        })
    }

    markAsRead = (data, isBack) => {
        const params = {
            cmd: "doChange",
            id: data.randomFieldId || data.id
        };
        api.save(params).then(datas => {
            const { message, status } = datas;

            if (status == 1) {
                Bubble.success(message);
                this.getSuggestList();
                if (isBack) {
                    if (window.em && window.em.checkJsApi('closeWindow')) {
                        window.em.closeWindow({
                            fail: (msg) => {
                                Bubble.error(JSON.stringify(msg))
                            }
                        });
                    }else{
                        this.history.go(-1)
                    }
                }
            } else {
                Bubble.warning(message);
            }
        })
    }

    openGroupSettingLayout = (datas, key) => {
        const { type, id } = datas;

        this.isEdit = true;
        this.groupType = type
        this.tabKey = key;
        this.groupid = id;
        this.history && this.history.push(this.operateGrouplayout.path);
    }

    openSuggestDetailLayout = (datas) => {
        this.suggestDetail = datas;
        this.history && this.history.push(this.suggestDetaillayout.path);
    }

    //删除常用组
    deleteGroup = (id) => {
        return new Promise((resolve, reject) => {
            const { listViewStore } = this.groupListAd;
            const selectedRowKeys = listViewStore.selectedRowKeys;

            const fn = (id) => {
                this.del({
                    cmd: "base",
                    groupid: id,
                }).then(datas => {
                    this.getGroupList();
                    resolve();
                }).catch(() => {
                    reject();
                });
            }
            if (id) {
                fn(id);
            } else {
                selectedRowKeys.forEach(id => {
                    fn(id);
                })
            }
        })
    }

    //删除成员
    deleteMember = (datas) => {
        this.renderDeleteConform(() => {
            this.del({
                cmd: "member",
                groupid: this.groupid,
                id: datas.id,
            }).then(() => {
                this.getMemberList();
            });
        });
    }

    //删除共享范围
    deleteShareScope = (datas) => {
        this.renderDeleteConform(() => {
            this.del({
                cmd: "share",
                groupid: this.groupid,
                id: datas.id,
            }).then(() => {
                this.getShareList();
            });
        });
    }

    //查询常用组所需的参数
    getQueryParams = () => {
        const {
            form: {
                formParams
            }
        } = this.groupListAd.searchAdvancedStore;
        return formParams;
    }


    //弹出删除确认框
    renderDeleteConform = (callback, type) => {
        const div = document.createElement("div");
        document.body.appendChild(div);

        const msg = (type === "batch") ? getLabel(385625, "确定要删除选择的记录吗？") : getLabel(15097, "确定要删除吗？");

        ReactDOM.render(<DeleteConfirm 
			msg={msg}
			handleOk={callback}
		/>, div);
    }

    handleHideCheck = () => {
        this.showCheck = false
    }

    openMultiHrmBrowser = () => {
        //单页的情况下，修改route，重新实例化BrowserHrm Store
        if (this.source === "op") {
            this.browserHrmStore = new BrowserHrm.Store({
                route: this.baseRoute,
                id: 'mulHrm'
            });
        }
        this.history && this.history.push(this.browserHrmStore.path);
    }

    openShareScopeAddLayout = () => {
        configNavigation({
            title:getLabel(505546, "添加共享"),
            left:{
                name:getLabel(1290, "返回"),
                action:() => {
                    configNavigation({
                        title: getLabel(518812, "编辑常用组")
                    })
                    this.history.go(-1);
                }
            },
            showCloseButton:false,
        });
        if (this.source === "op") {
            this.shareScopeAddlayout = new RouteLayout.Store({
                route: this.baseRoute,
                id: "addShare"
            });
            this.shareForm = new Form.Store({
                route: `${this.baseRoute}/addShare`,
            });
        }
        this.history && this.history.push(this.shareScopeAddlayout.path);
        this.getForm({ cmd: "share" });
    }

    openSuggestSearchLayout = () => {
        this.history && this.history.push(this.suggestSearchStore.path);
    }

    setHistory = (history) => {
        this.history = history;
    }

    setGroupId = (id) => {
        this.groupid = id;
    }

    resetGroupId = () => {
        this.groupid = "";
    }

    refreshMainPage = () => {
        this.getGroupList();
        this.basicForm = new Form.Store({
            route: '/group/list/operate',
        });
    }

    splitUrl = (search) => {
        const paramArr = search.slice(1).split("&");
        const obj = {};
        paramArr.forEach(item => {
            const [key, value] = item.split("=");
            obj[key] = value;
        });
        return obj;
    }

}